import request from './index'
import { isDef } from '../tools'
import { message } from 'ant-design-vue';
interface ReqConfig {
    successTip?: boolean; // 请求成功时是否提示
    errorTip?: boolean; // 请求失败时是否提示
    successMsg?: string; // 请求成功时提示内容
    errorMsg?: string; // 请求失败时提示内容
}
const get = (api: string, params: any, config?: ReqConfig) => {
    const _config = setConfig(config);
    return httpRequest(api, params, _config, 'GET');
}

const post = (api: string, params: any, config?: ReqConfig) => {
    const _config = setConfig(config);
    return httpRequest(api, params, _config, 'POST');
}
const put = (api: string, params: any, config?: ReqConfig) => {
    const _config = setConfig(config);
    return httpRequest(api, params, _config, 'PUT');
}
const del = (api: string, params: any, config?: ReqConfig) => {
    const _config = setConfig(config);
    return httpRequest(api, params, _config, 'DELETE');
}
// 设置请求配置
const setConfig = (config?: ReqConfig): ReqConfig => {
    if (config) {
        !isDef(config.successTip) && (config.successTip = true);
        !isDef(config.errorTip) && (config.errorTip = true);
    } else {
        config = {
            successTip: true,
            errorTip: true
        };
    }
    return config;
}

const httpRequest = (api: string, params: any, options: ReqConfig, method: 'GET' | 'POST' | 'PUT' | 'DELETE') => {
    return new Promise((resolve, reject) => {
        let requestParams = {};
        if (method === 'GET' || method === 'DELETE') {
            requestParams = {
                params,
            }
        } else {
            requestParams = {
                data: params
            }
        }
        request({
            url: api,
            method: method,
            ...requestParams
        }).then((res: any) => {
            if (isDef(res.code) && res.code === 1 && options.errorTip) {
                message.error(options.errorMsg || res.msg, 2)
            }
            if(isDef(res.code) && res.code === 0 && options.successTip) {
                message.success(options.successMsg || res.msg, 2)
            }
            resolve(res);
        }).catch(err => {
            reject({ code: 2 })
        })
    })
}

export default {
    get,
    post,
    put,
    del
}